package com.ten.security.aspect;

import com.ten.common.core.util.JWTUtil;
import com.ten.security.annotation.RquiresPermissions;
import com.ten.security.exception.PermissionException;
import com.ten.security.utils.WebUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;

/**
 * @author ：Q大侠
 * @date ：Created in 2022/12/2 14:44
 * @description：
 * @modified By：
 * @version:
 */
//交予spring容器创建与管理
@Component
//表示该类为切面类
@Aspect
public class PreAuthorizeAspect {
    //切点:在哪些位置添加上aop切面
    @Pointcut(value = "@annotation(com.ten.security.annotation.RquiresPermissions)")
    public void pointcut(){}

    //环绕通知
    @Around(value = "pointcut()")
    public Object around(ProceedingJoinPoint joinPoint){
        //获取连接点的方法--获取使用了RequiresPermissions注解的方法对象
        MethodSignature method = (MethodSignature) joinPoint.getSignature();
        //获取方法上的RequiresPermissions
        checkAnnotation(method.getMethod());
        Object result = null;
        //回调接口方法
        try {
            result = joinPoint.proceed();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return result;
    }
    private void checkAnnotation(Method method){
        RquiresPermissions annotation = method.getAnnotation(RquiresPermissions.class);
        if (annotation!=null){
            //获取注解上的权限信息
            String value = annotation.value();
        //判断所登录用户师傅具有注解上的权限
            //获取用户权限--获取token
            HttpServletRequest request = WebUtil.getRequest();
            String token = request.getHeader("token");
            System.out.println(token);
            //获取用户权限--获取用户权限
            Map<String, Object> map = JWTUtil.getTokenChaim(token);
            List<String> permissions = (List<String>) map.get("premissions");
            //判断用户是否具有该权限--无则抛出异常
            if (!permissions.contains(value)){
                throw new PermissionException("权限不足!");
            }
        }
    }
}
